#!/bin/bash

# PCF API Server Demo - Test Script
# This script tests the PCF API server endpoints

set -e

# Configuration
BASE_URL="http://localhost:1026"
API_ENDPOINT="/service/user/PcfSubscription"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    local status=$1
    local message=$2
    case $status in
        "SUCCESS")
            echo -e "${GREEN}✓${NC} $message"
            ;;
        "ERROR")
            echo -e "${RED}✗${NC} $message"
            ;;
        "INFO")
            echo -e "${BLUE}ℹ${NC} $message"
            ;;
        "WARNING")
            echo -e "${YELLOW}⚠${NC} $message"
            ;;
    esac
}

# Function to test an endpoint
test_endpoint() {
    local endpoint=$1
    local description=$2
    local expected_status=${3:-200}
    
    print_status "INFO" "Testing $description..."
    
    response=$(curl -s -w "%{http_code}" -o /tmp/response.json "$BASE_URL$endpoint" 2>/dev/null)
    http_code="${response: -3}"
    
    if [ "$http_code" -eq "$expected_status" ]; then
        print_status "SUCCESS" "$description passed (HTTP $http_code)"
        if [ -s /tmp/response.json ]; then
            echo "  Response preview: $(head -c 100 /tmp/response.json)..."
        fi
        return 0
    else
        print_status "ERROR" "$description failed (HTTP $http_code, expected $expected_status)"
        if [ -s /tmp/response.json ]; then
            echo "  Error response: $(cat /tmp/response.json)"
        fi
        return 1
    fi
}

# Function to test PCF subscription with MSISDN
test_pcf_subscription() {
    local msisdn=$1
    local description="PCF subscription for $msisdn"
    
    print_status "INFO" "Testing $description..."
    
    response=$(curl -s -w "%{http_code}" -o /tmp/response.json "$BASE_URL$API_ENDPOINT?number=$msisdn" 2>/dev/null)
    http_code="${response: -3}"
    
    if [ "$http_code" -eq 200 ]; then
        print_status "SUCCESS" "$description passed (HTTP $http_code)"
        
        # Parse JSON response to check structure
        if command -v jq >/dev/null 2>&1; then
            code=$(jq -r '.code' /tmp/response.json 2>/dev/null || echo "null")
            message=$(jq -r '.message' /tmp/response.json 2>/dev/null || echo "null")
            records_count=$(jq -r '.result.records | length' /tmp/response.json 2>/dev/null || echo "0")
            
            echo "  Code: $code"
            echo "  Message: $message"
            echo "  Records count: $records_count"
            
            if [ "$code" = "200" ] && [ "$records_count" -gt 0 ]; then
                print_status "SUCCESS" "Response structure is valid"
                return 0
            else
                print_status "WARNING" "Response structure may be invalid"
                return 1
            fi
        else
            echo "  Response preview: $(head -c 200 /tmp/response.json)..."
            return 0
        fi
    else
        print_status "ERROR" "$description failed (HTTP $http_code)"
        if [ -s /tmp/response.json ]; then
            echo "  Error response: $(cat /tmp/response.json)"
        fi
        return 1
    fi
}

# Main test execution
echo "PCF API Server Demo - Test Suite"
echo "================================"

# Check if server is running
print_status "INFO" "Checking if server is running..."

if curl -s "$BASE_URL/health" >/dev/null 2>&1; then
    print_status "SUCCESS" "Server is running"
else
    print_status "ERROR" "Server is not running. Please start the server first:"
    echo "  python app.py"
    exit 1
fi

# Initialize counters
total_tests=0
passed_tests=0

# Test basic endpoints
echo ""
echo "Testing basic endpoints..."

((total_tests++))
if test_endpoint "/health" "Health check"; then
    ((passed_tests++))
fi

((total_tests++))
if test_endpoint "/" "Root endpoint"; then
    ((passed_tests++))
fi

((total_tests++))
if test_endpoint "/msisdns" "List MSISDNs"; then
    ((passed_tests++))
fi

# Test API functionality
echo ""
echo "Testing API functionality..."

((total_tests++))
if test_endpoint "$API_ENDPOINT" "Missing parameter test" 400; then
    ((passed_tests++))
fi

# Test PCF subscription with different MSISDNs
echo ""
echo "Testing PCF subscription endpoints..."

test_msisdns=("8613764010195" "8613800138000" "8613900000000")

for msisdn in "${test_msisdns[@]}"; do
    ((total_tests++))
    if test_pcf_subscription "$msisdn"; then
        ((passed_tests++))
    fi
done

# Summary
echo ""
echo "================================"
echo "Test Summary:"
echo "  Total tests: $total_tests"
echo "  Passed: $passed_tests"
echo "  Failed: $((total_tests - passed_tests))"

if [ $passed_tests -eq $total_tests ]; then
    print_status "SUCCESS" "All tests passed! PCF API Server is working correctly."
    exit 0
else
    print_status "WARNING" "Some tests failed. Please check the server configuration."
    exit 1
fi 